import 'package:flutter/material.dart';
import 'package:hi_net/navigator/hi_navigator.dart';
import 'package:hi_net/page/home_tab_page.dart';
import 'package:hi_net/page/mine_page.dart';
import 'package:hi_net/page/video_detail_page.dart';
import 'package:hi_net/widget/hi_navigation_bar.dart';
import 'package:hi_net/widget/hi_tab.dart';
import 'package:hi_net/widget/loading_container.dart';

import '../http/core/hi_net_error.dart';
import '../http/dio/home_dao.dart';
import '../model/home_mo.dart';
import '../model/local_data.dart';
import '../util/toast.dart';
import '../core/hi_state.dart';
import '../util/view_util.dart';

class HomePage extends StatefulWidget {
  final ValueChanged<int>? onJumpTo;

  const HomePage({super.key, this.onJumpTo});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends HiState<HomePage>
    with AutomaticKeepAliveClientMixin, TickerProviderStateMixin, WidgetsBindingObserver {
  late RouteChangeListener listener;
  late TabController _controller;

  List<CategoryMo> categoryList = [];
  List<BannerMo> bannerList = [];

  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance?.addObserver(this);
    _controller = TabController(length: categoryList.length, vsync: this);
    HiNavigator.getInstance.addListener(listener = (current, pre) {
      print('home:current:${current.page}');
      print('home:pre:${pre?.page}');
      if (widget == current.page || current.page is HomePage) {
        print('打开了首页:onResume');
      } else if (widget == pre?.page || pre?.page is HomePage) {
        print('首页:onPause');
      }

      //当页面返回到首页恢复首页的状态栏样式
      if (pre?.page is VideoDetailPage && current.page is! MinePage) {
        var statusStyle = StatusStyle.DARK_CONTENT;
        changeStatusBar(color: Colors.white, statusStyle: statusStyle);
      }
    });
    loadData2();
  }

  @override
  void dispose() {
    WidgetsBinding.instance?.removeObserver(this);
    HiNavigator.getInstance.removeListener(listener);
    _controller.dispose();
    super.dispose();
  }

  ///监听应用生命周期变化
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    print(':didChangeAppLifecycleState:$state');
    switch (state) {
      case AppLifecycleState.inactive: // 处于这种状态的应用程序应该假设它们可能在任何时候暂停。
        break;
      case AppLifecycleState.resumed: //从后台切换前台，界面可见
        //fix Android压后台首页状态栏字体颜色变白，详情页状态栏字体变黑问题
        changeStatusBar();
        break;
      case AppLifecycleState.paused: // 界面不可见，后台
        break;
      case AppLifecycleState.detached: // APP结束时调用
        break;
      case AppLifecycleState.hidden:
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: LoadingContainer(
          isLoading: _isLoading,
          child: Column(
            children: [
              HiNavigationBar(
                height: 50,
                child: _appBar(),
                color: Colors.white,
                statusStyle: StatusStyle.DARK_CONTENT,
              ),
              Container(
                child: _tabBar(),
                decoration: bottomBoxShadow(),
              ),
              Flexible(
                  child: TabBarView(
                controller: _controller,
                children: categoryList.map((tab) {
                  return HomeTabPage(categoryName: tab.name, bannerList: tab.name == '推荐' ? bannerList : []);
                }).toList(),
              )),
            ],
          )),
    );
  }

  @override
  bool get wantKeepAlive => true;

  ///自定义顶部tab
  _tabBar() {
    return HiTab(
      categoryList.map((tab) {
        return Tab(
          child: Text(
            tab.name,
            style: const TextStyle(fontSize: 16),
          ),
        );
      }).toList(),
      controller: _controller,
      fontSize: 16,
      borderWidth: 3,
      unselectedLabelColor: Colors.black54,
      insets: 2,
    );
  }

  void loadData() async {
    try {
      HomeMo result = await HomeDao.get('推荐');
      print('loadData():$result');
      if (result.categoryList != null) {
        //tab长度变化后需要重新创建TabController
        _controller = TabController(length: result.categoryList?.length ?? 0, vsync: this);
      }
      setState(() {
        categoryList = result.categoryList ?? [];
        bannerList = result.bannerList ?? [];
        _isLoading = false;
      });
    } on NeedAuth catch (e) {
      print(e);
      showWarnToast(e.message);
      setState(() {
        _isLoading = false;
      });
    } on HiNetError catch (e) {
      print(e);
      showWarnToast(e.message);
      setState(() {
        _isLoading = false;
      });
    }
  }

  void loadData2() async {
    try {
      List<CategoryMo> list = [
        CategoryMo('推荐', 10),
        CategoryMo('热门', 10),
        CategoryMo('追播', 10),
        CategoryMo('影视', 10),
        CategoryMo('搞笑', 10),
        CategoryMo('日常', 10),
        CategoryMo('综合', 10),
        CategoryMo('手机游戏', 10),
        CategoryMo('短片·手书', 10),
      ];
      List<BannerMo> banners = getBanners();

      if (list != null) {
        //tab长度变化后需要重新创建TabController
        _controller = TabController(length: list?.length ?? 0, vsync: this);
      }
      Future.delayed(const Duration(seconds: 2), () {
        setState(() {
          categoryList = list;
          bannerList = banners;
          _isLoading = false;
        });
      });
    } on NeedAuth catch (e) {
      print(e);
      showWarnToast(e.message);
    } on HiNetError catch (e) {
      print(e);
      showWarnToast(e.message);
    }
  }

  _appBar() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 15),
      child: Row(
        children: [
          InkWell(
            onTap: () {
              if (widget.onJumpTo != null) widget.onJumpTo!(3);
            },
            child: ClipRRect(
              borderRadius: BorderRadius.circular(23),
              child: const Image(height: 46, width: 46, image: AssetImage('assets/images/avatar.png')),
            ),
          ),
          Expanded(
              child: Padding(
            padding: const EdgeInsets.symmetric(horizontal: 15),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(16),
              child: Container(
                padding: const EdgeInsets.only(left: 10),
                height: 32,
                alignment: Alignment.centerLeft,
                decoration: BoxDecoration(color: Colors.grey[100]),
                child: const Icon(Icons.search, color: Colors.grey),
              ),
            ),
          )),
          const Icon(
            Icons.explore_outlined,
            color: Colors.grey,
          ),
          const Padding(
            padding: EdgeInsets.only(left: 12),
            child: Icon(
              Icons.mail_outline,
              color: Colors.grey,
            ),
          ),
        ],
      ),
    );
  }
}
